import { ref, onMounted, onUnmounted, computed } from 'vue'

// 响应式断点
export const BREAKPOINTS = {
  xs: 480,
  sm: 768,
  md: 992,
  lg: 1200,
  xl: 1920
} as const

// 响应式状态管理
export function useResponsive() {
  const isMobile = ref(false)
  const isTablet = ref(false)
  const isDesktop = ref(false)
  const isLandscape = ref(false)
  const screenWidth = ref(0)
  const screenHeight = ref(0)

  const updateScreenSize = () => {
    screenWidth.value = window.innerWidth
    screenHeight.value = window.innerHeight
    
    isMobile.value = screenWidth.value <= BREAKPOINTS.sm
    isTablet.value = screenWidth.value > BREAKPOINTS.sm && screenWidth.value <= BREAKPOINTS.md
    isDesktop.value = screenWidth.value > BREAKPOINTS.md
    isLandscape.value = screenWidth.value > screenHeight.value
  }

  const handleResize = () => {
    updateScreenSize()
  }

  const handleOrientationChange = () => {
    setTimeout(updateScreenSize, 100) // 延迟更新，等待旋转完成
  }

  onMounted(() => {
    updateScreenSize()
    window.addEventListener('resize', handleResize)
    window.addEventListener('orientationchange', handleOrientationChange)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    window.removeEventListener('orientationchange', handleOrientationChange)
  })

  return {
    isMobile,
    isTablet,
    isDesktop,
    isLandscape,
    screenWidth,
    screenHeight,
    BREAKPOINTS
  }
}

// 触摸设备检测
export function useTouchDevice() {
  const isTouchDevice = ref(false)
  
  onMounted(() => {
    isTouchDevice.value = 'ontouchstart' in window || navigator.maxTouchPoints > 0
  })
  
  return { isTouchDevice }
}

// 响应式类名生成器
export function getResponsiveClass(baseClass: string, breakpoint?: keyof typeof BREAKPOINTS) {
  return breakpoint ? `${baseClass}--${breakpoint}` : baseClass
}

// 移动端header宽度监听器
export function useMobileHeaderWidthMonitor() {
  const mobileHeaderRef = ref<HTMLElement>()
  const headerWidth = ref(0)
  const screenWidth = ref(0)
  const isWidthValid = ref(true)
  
  // 从API获取屏幕宽度（这里使用模拟API，实际项目中替换为真实API）
  const getScreenWidthFromAPI = async (): Promise<number> => {
    try {
      // 模拟API调用，实际项目中替换为真实的API调用
      // const response = await fetch('/api/screen-info')
      // const data = await response.json()
      // return data.screenWidth || window.innerWidth
      
      // 临时使用浏览器API，实际项目中应该从后端获取
      return window.innerWidth
    } catch (error) {
      console.warn('无法从API获取屏幕宽度，使用浏览器默认值:', error)
      return window.innerWidth
    }
  }
  
  // 更新屏幕宽度
  const updateScreenWidth = async () => {
    screenWidth.value = await getScreenWidthFromAPI()
  }
  
  // 检查header宽度是否有效
  const checkHeaderWidth = () => {
    if (mobileHeaderRef.value) {
      const currentHeaderWidth = mobileHeaderRef.value.offsetWidth
      headerWidth.value = currentHeaderWidth
      
      // 确保header宽度小于屏幕宽度，留出安全边距
      const safeMargin = 20 // 20px的安全边距
      const maxAllowedWidth = screenWidth.value - safeMargin
      
      isWidthValid.value = currentHeaderWidth <= maxAllowedWidth
      
      if (!isWidthValid.value) {
        console.warn(`移动端header宽度(${currentHeaderWidth}px)超过安全宽度(${maxAllowedWidth}px)`)
        
        // 自动调整header宽度
        if (mobileHeaderRef.value) {
          mobileHeaderRef.value.style.maxWidth = `${maxAllowedWidth}px`
          mobileHeaderRef.value.style.overflow = 'hidden'
        }
      }
    }
  }
  
  // 设置ResizeObserver监听header尺寸变化
  const setupHeaderObserver = () => {
    if (mobileHeaderRef.value && window.ResizeObserver) {
      const resizeObserver = new ResizeObserver(() => {
        checkHeaderWidth()
      })
      resizeObserver.observe(mobileHeaderRef.value)
      
      return () => {
        resizeObserver.disconnect()
      }
    }
  }
  
  // 设置屏幕尺寸监听
  const setupScreenObserver = () => {
    const handleScreenResize = () => {
      updateScreenWidth()
      checkHeaderWidth()
    }
    
    window.addEventListener('resize', handleScreenResize)
    window.addEventListener('orientationchange', handleScreenResize)
    
    return () => {
      window.removeEventListener('resize', handleScreenResize)
      window.removeEventListener('orientationchange', handleScreenResize)
    }
  }
  
  // 初始化监听器
  const initializeMonitor = async () => {
    await updateScreenWidth()
    checkHeaderWidth()
    
    const cleanupHeader = setupHeaderObserver()
    const cleanupScreen = setupScreenObserver()
    
    return () => {
      cleanupHeader?.()
      cleanupScreen?.()
    }
  }
  
  // 手动检查宽度（用于外部调用）
  const validateHeaderWidth = () => {
    checkHeaderWidth()
  }
  
  // 获取宽度状态信息
  const getWidthStatus = computed(() => ({
    headerWidth: headerWidth.value,
    screenWidth: screenWidth.value,
    isWidthValid: isWidthValid.value,
    safeWidth: screenWidth.value - 2,
    overflow: headerWidth.value > (screenWidth.value - 20)
  }))
  
  return {
    mobileHeaderRef,
    headerWidth,
    screenWidth,
    isWidthValid,
    initializeMonitor,
    validateHeaderWidth,
    getWidthStatus
  }
}

// 通用header宽度监听器（适用于任何header元素）
export function useHeaderWidthMonitor(headerType: 'app' | 'mobile' = 'app') {
  const headerRef = ref<HTMLElement>()
  const headerWidth = ref(0)
  const screenWidth = ref(0)
  const isWidthValid = ref(true)
  const headerTypeName = headerType === 'app' ? '应用' : '移动端'
  
  // 从API获取屏幕宽度
  const getScreenWidthFromAPI = async (): Promise<number> => {
    try {
      // 这里可以集成screenService
      // import { screenService } from '@/api/screenService'
      // const response = await screenService.getScreenInfo()
      // return response.data.viewportWidth
      
      // 临时使用浏览器API
      return window.innerWidth
    } catch (error) {
      console.warn(`无法从API获取屏幕宽度，使用浏览器默认值:`, error)
      return window.innerWidth
    }
  }
  
  // 更新屏幕宽度
  const updateScreenWidth = async () => {
    screenWidth.value = await getScreenWidthFromAPI()
  }
  
  // 检查header宽度是否有效
  const checkHeaderWidth = () => {
    if (headerRef.value) {
      const currentHeaderWidth = headerRef.value.offsetWidth
      headerWidth.value = currentHeaderWidth
      
      // 确保header宽度小于屏幕宽度，留出安全边距
      const safeMargin = headerType === 'app' ? 40 : 0 // 移动端不需要安全边距
      const maxAllowedWidth = screenWidth.value - safeMargin
      
      isWidthValid.value = currentHeaderWidth <= maxAllowedWidth
    }
  }
  
  // 设置ResizeObserver监听header尺寸变化
  const setupHeaderObserver = () => {
    if (headerRef.value && window.ResizeObserver) {
      const resizeObserver = new ResizeObserver(() => {
        checkHeaderWidth()
      })
      resizeObserver.observe(headerRef.value)
      
      return () => {
        resizeObserver.disconnect()
      }
    }
  }
  
  // 设置屏幕尺寸监听
  const setupScreenObserver = () => {
    const handleScreenResize = () => {
      updateScreenWidth()
      checkHeaderWidth()
    }
    
    window.addEventListener('resize', handleScreenResize)
    window.addEventListener('orientationchange', handleScreenResize)
    
    return () => {
      window.removeEventListener('resize', handleScreenResize)
      window.removeEventListener('orientationchange', handleScreenResize)
    }
  }
  
  // 初始化监听器
  const initializeMonitor = async () => {
    await updateScreenWidth()
    checkHeaderWidth()
    
    const cleanupHeader = setupHeaderObserver()
    const cleanupScreen = setupScreenObserver()
    
    return () => {
      cleanupHeader?.()
      cleanupScreen?.()
    }
  }
  
  // 手动检查宽度（用于外部调用）
  const validateHeaderWidth = () => {
    checkHeaderWidth()
  }
  
  // 获取宽度状态信息
  const getWidthStatus = computed(() => ({
    headerWidth: headerWidth.value,
    screenWidth: screenWidth.value,
    isWidthValid: isWidthValid.value,
    safeWidth: screenWidth.value - (headerType === 'app' ? 40 : 0),
    overflow: headerWidth.value > (screenWidth.value - (headerType === 'app' ? 40 : 0)),
    headerType: headerTypeName,
    widthDiff: Math.abs(headerWidth.value - screenWidth.value)
  }))
  
  // 获取CSS变量形式的宽度限制
  const getWidthCSSVars = computed(() => ({
    '--max-header-width': `${screenWidth.value - (headerType === 'app' ? 40 : 0)}px`,
    '--safe-margin': `${headerType === 'app' ? 40 : 0}px`
  }))
  
  return {
    headerRef,
    headerWidth,
    screenWidth,
    isWidthValid,
    initializeMonitor,
    validateHeaderWidth,
    getWidthStatus,
    getWidthCSSVars
  }
}

// 响应式样式计算器
export function getResponsiveValue<T>(
  mobile: T,
  tablet: T,
  desktop: T,
  currentBreakpoint: keyof typeof BREAKPOINTS
): T {
  switch (currentBreakpoint) {
    case 'xs':
    case 'sm':
      return mobile
    case 'md':
      return tablet
    case 'lg':
    case 'xl':
      return desktop
    default:
      return desktop
  }
}

// 媒体查询工具
export const mediaQueries = {
  xs: `@media (max-width: ${BREAKPOINTS.xs}px)`,
  sm: `@media (max-width: ${BREAKPOINTS.sm}px)`,
  md: `@media (max-width: ${BREAKPOINTS.md}px)`,
  lg: `@media (max-width: ${BREAKPOINTS.lg}px)`,
  xl: `@media (max-width: ${BREAKPOINTS.xl}px)`,
  
  // 向上断点
  smUp: `@media (min-width: ${BREAKPOINTS.xs + 1}px)`,
  mdUp: `@media (min-width: ${BREAKPOINTS.sm + 1}px)`,
  lgUp: `@media (min-width: ${BREAKPOINTS.md + 1}px)`,
  xlUp: `@media (min-width: ${BREAKPOINTS.lg + 1}px)`,
  
  // 横屏/竖屏
  landscape: '@media (orientation: landscape)',
  portrait: '@media (orientation: portrait)',
  
  // 触摸设备
  touch: '@media (hover: none) and (pointer: coarse)',
  noTouch: '@media (hover: hover) and (pointer: fine)',
  
  // 高分辨率
  retina: '@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)',
  
  // 深色模式
  dark: '@media (prefers-color-scheme: dark)',
  light: '@media (prefers-color-scheme: light)',
  
  // 减少动画
  reducedMotion: '@media (prefers-reduced-motion: reduce)'
}

// 响应式网格系统
export const gridSystem = {
  // 移动端优先的网格列数
  getGridColumns: (breakpoint: keyof typeof BREAKPOINTS) => {
    switch (breakpoint) {
      case 'xs':
        return 1
      case 'sm':
        return 2
      case 'md':
        return 3
      case 'lg':
        return 4
      case 'xl':
        return 6
      default:
        return 4
    }
  },
  
  // 响应式间距
  getSpacing: (breakpoint: keyof typeof BREAKPOINTS) => {
    switch (breakpoint) {
      case 'xs':
        return 8
      case 'sm':
        return 12
      case 'md':
        return 16
      case 'lg':
        return 20
      case 'xl':
        return 24
      default:
        return 20
    }
  }
}
